<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use App\Models\FeeGood;
use App\Models\FeeItem;
use App\Models\Set;
use App\Models\Order as TOrder;
use App\Models\GoodItem;
use App\Models\Good;
use App\Models\GoodOption;
use App\Models\Agent;
use App\Models\Service;

class Order extends ApiController{
    public function index(Request $req){
        $page = $req->post('page',1);
        $status = $req->post('status',0);
        $kword = $req->post('kword','');
        $size = 5;
        $list = TOrder::where('mid',$req->mem->id)->orderByDesc('id')->offset(($page-1)*$size)->limit($size);
        if ($status == 3) $list->where('status',-1); 
        elseif ($status > 0) $list->where('status',$status); 
        if ($kword) $list->where("ordersn",$kword);
        $orders = [];
        foreach ($list->get() as $value) {
            $o = array('ordersn'=>$value->ordersn,'price'=>$value->price,'createtime'=>date('Y-m-d H:i',$value->createtime),'status'=>$value->status,'nums'=>$value->nums);
            if ($value->status == -1) $o['statusstr'] = '已退款';
            elseif ($value->status == 1) $o['statusstr'] = '进行中';
            elseif ($value->status == 2) $o['statusstr'] = '已完成';
            else $o['statusstr'] = '未支付';
            if ($value->reason) $o['reason'] = $value->reason;
            $o['good'] = [];
            if ($value->type < 10) {
                if ($value->type == 0) {
                    $o['good']['title'] = '话费';
                    $o['good']['logo'] = '/static/hf_icon.jpeg';
                }elseif ($value->type == 1) {
                    $o['good']['title'] = '电费';
                    $o['good']['logo'] = '/static/df_icon.png';
                }elseif ($value->type == 2) {
                    $o['good']['title'] = '燃气';
                    $o['good']['logo'] = '/static/rq_icon.png';
                }
                $o['good']['optiontitle'] = FeeGood::where('id',$value->gid)->value('title').'元';
            }else{
                $g = Good::find($value->gid);
                $o['good']['title'] = $g->title;
                $o['good']['logo'] = getImage($g->logo,1);
                $p = json_decode($value->param,1);
                $o['good']['optiontitle'] =$p['title'];
            }
            $orders[] = $o;
        }
        $data = ['list'=>$orders];
        if ($page == 1) {
            $h = date('H:i');
            $url = getImage(Service::where('aid',0)->where("starttime",'<=',$h)->where('endtime','>',$h)->value('url'),1);
            if ($url) $data['server'] = $url;
            $set = Set::getSet('base');
            $data['sharedata'] = array(
                    'title'=> $set['title'],
                    'imgUrl'=>"https://".$req->host()."/static/hf_icon.jpeg",
                    'desc'=>$set['desc']??$set['title'],
                    'link'=>"https://".$req->host()."/".$req->shopagent->code
            );
        }
        wxresp(1,$data);
    }
    
    public function pay(Request $req){
        $gid = $req->post('gid');
        $type = $req->post('type');
        $mobile = $req->post('mobile');
        if (empty($mobile)) wxresp(0,'号码不能为空');
        if ($type == 0 && strlen($mobile) != 11) wxresp(0,'请输入正确手机号码');
        $order = array(
                'paid'=>$req->shopagent->paid,
                'aid'=>$req->shopagent->id,
                'mid'=>$req->mem->id,
                'ordersn'=>'SP'.date('YmdHis').random(6,1),
                'nums'=>$mobile,
                'type'=>$type,
                'createtime'=>time()
        );
        if ($type < 10) {
            $good = FeeGood::find($gid);
            if (empty($good) || $good->status) wxresp(0,'该商品已下架');
            $item = FeeItem::where('gid',$gid)->where('status',0)->orderBy('costprice');
            if ($type == 1){
                $order['param'] = $req->post('data');
                $p = json_decode($order['param'],1);
                $item->whereRaw("(extra='' or extra='{$p['type']}')");
            }
            $item = $item->first();
            if (empty($item)) wxresp(0,'该商品已下架');
            $item->marketprice = $good->marketprice;
            $item->agentprice = $good->agentprice;
        }else{
            $item = GoodOption::find($gid);
            if (empty($item) || $item->status) wxresp(0,'该商品已下架');
            $good = Good::find($item->gid);
            if (empty($good) || $good->status) wxresp(0,'该商品已下架');
            $gitem = GoodItem::where('oid',$item->id)->where('status',0)->orderBy('costprice')->first();
            if (empty($gitem)) wxresp(0,'该商品已下架');
            $order['param'] = json_encode(array('oid'=>$item->id,'title'=>$item->ptitle.'-'.$item->title));
            $item->costprice = $gitem->costprice;
        }
        $agentprice = json_decode($item->agentprice,1);
        $order['gid'] = $good->id;
        $order['costprice'] = $item->costprice;
        $order['price'] = round($order['costprice'] + $item->marketprice,2);
        $ap = $agentprice[$req->shopagent->level]??$item->marketprice;
        $order['agentprice'] = round($order['costprice'] + $ap,2);
//         if ($req->shopagent->credit < $order['agentprice']) wxresp(0,'商户额度不足，请联系客服');
        
        $order['reback'] = round($item->marketprice - $ap,2);
        if ($req->shopagent->paid > 0 && $ap > 0){
            $plevel = $plevel = Agent::where('id',$req->shopagent->paid)->value('level');
            if ($plevel > $req->shopagent->level) $order['preback'] = round($ap - ($agentprice[$plevel]??$ap),2);
        }
        $params = array(
                'openid'=>$req->mem->openid,
                'body'=>'产品充值',
                'price'=>$order['price'],
                'orderno'=>$order['ordersn'],
                'notify_url'=>'https://'.$req->host()."/notify/".$order['ordersn']
        );
        $set = Set::getSet('wxpay');
        $pay = new \WxPay($set);
        $res = $pay->wxappPay($params);
        if($res['code'] == 0) wxresp(0,$res['msg']);
        $orderid = TOrder::insertGetId($order);
        $preresult = $res['paydata'];
        $preresult['orderid'] = $orderid;
        wxresp(1,array('data'=>$preresult));
    }
}